package trilium

import (
	"context"
	"gitee.com/Luna-CY/hui-hui/internal/application/app"
	"gitee.com/Luna-CY/hui-hui/internal/interface/application"
	"gitee.com/Luna-CY/hui-hui/internal/logger"
	"gitee.com/Luna-CY/hui-hui/internal/runtime"
	"gitee.com/Luna-CY/hui-hui/internal/toolbox/processor"
	"os"
	"path/filepath"
	"sync"
)

const defaultPort = 8602

// rootPath 服务器目录
var rootPath = filepath.Join(runtime.ApplicationRoot, "trilium")

// internalConfigPath 内部配置文件路径
var internalConfigPath = filepath.Join(runtime.ConfigRoot, "trilium.v1.json")

// logFolder 日志目录
var logFolder = filepath.Join(rootPath, "logs")

// dataDir 数据目录
var dataDir = filepath.Join(runtime.Data, "trilium")

// configFilePath 服务器配置文件路径
var configFilePath = filepath.Join(dataDir, "config.ini")

var once sync.Once
var instance *Trilium

func Single(processor *processor.Processor) *Trilium {
	once.Do(func() {
		var config = new(application.TriliumConfig)
		config.Listen = "127.0.0.1"
		config.Port = defaultPort

		instance = &Trilium{processor: processor}
		instance.UpdateState(application.NotInstall, 0, "")
		instance.Application.SetConfig(config)

		// 本地自检
		if err := instance.CheckLocationState(context.Background()); nil != err {
			logger.GetLogger().Sugar().Errorf("检查Trilium服务状态失败，失败原因: %s", err)

			os.Exit(1)
		}

		// 加载本地配置
		if err := instance.LoadFromDisk(nil, internalConfigPath); nil != err {
			logger.GetLogger().Sugar().Errorf("加载Trilium配置文件失败，失败原因: %s", err)

			os.Exit(1)
		}
	})

	return instance
}

type Trilium struct {
	app.Application[application.TriliumConfig]

	processor *processor.Processor
}
